#include "draw_chart.h"

#include <QChartView>
#include <QChart>
#include <QLineSeries>
#include <QValueAxis>
#include <QCategoryAxis>

#include <QGridLayout>
#include <QGroupBox>
#include <QSplitter>
#include <QRegularExpression>
#include <QFileDialog>
#include <QPainter>
#include <QDebug>
#include <QApplication>

DrawChart::DrawChart(QObject *parent) : QObject(parent)
{
    qDebug() << "DrawChart 初始化";
}

// 数据解析函数 - 只解析包含S_BMS关键字的行
void DrawChart::parseData(const QString &data)
{
    qDebug() << "开始解析数据";
    sBmsData.clear();
    bmsFData.clear();

    QStringList lines = data.split('\n');
    qDebug() << "总行数:" << lines.size();

    int sBmsCount = 0;
    int bmsFCount = 0;

    for (int i = 0; i < lines.size(); ++i) {
        const QString &line = lines[i].trimmed();
        if (line.isEmpty()) continue;

        // 只解析包含S_BMS关键字的行
        if (line.contains("S_BMS")) {
            parseS_BMSData(line);
            sBmsCount++;
        }

        // 解析BMS F数据
        if (line.contains("F BMS")) {
            parseBMSFData(line);
            bmsFCount++;
        }
    }

    qDebug() << "解析完成: S_BMS=" << sBmsData.size() << "(" << sBmsCount << "行包含关键字), BMSF=" << bmsFData.size() << "(" << bmsFCount << "行包含关键字)";
}

// 绘制 S_BMS 图表
void DrawChart::drawS_BMSChart(QWidget *parentWidget)
{
    qDebug() << "开始绘制 S_BMS 图表";

    if (sBmsData.isEmpty()) {
        emit errorOccurred("没有 S_BMS 数据可绘制图表");
        return;
    }

    if (!parentWidget) {
        emit errorOccurred("父部件为空，无法绘制图表");
        return;
    }

    // 清除旧图表
    clearCharts(parentWidget);

    try {
        QChartView *chartView = createS_BMSChart();
        if (chartView) {
            setupChartLayout(parentWidget, chartView, QString("S_BMS 数据图表 (共%1个数据点)").arg(sBmsData.size()));
            qDebug() << "S_BMS 图表绘制完成";
            emit chartDrawn();
        } else {
            emit errorOccurred("S_BMS 图表创建失败");
        }
    } catch (const std::exception& e) {
        emit errorOccurred(QString("绘制 S_BMS 图表时发生异常: %1").arg(e.what()));
    } catch (...) {
        emit errorOccurred("绘制 S_BMS 图表时发生未知异常");
    }
}

// 绘制 BMS F 图表
void DrawChart::drawBMSFChart(QWidget *parentWidget)
{
    qDebug() << "开始绘制 BMS F 图表";

    if (bmsFData.isEmpty()) {
        emit errorOccurred("没有 BMS F 数据可绘制图表");
        return;
    }

    if (!parentWidget) {
        emit errorOccurred("父部件为空，无法绘制图表");
        return;
    }

    // 清除旧图表
    clearCharts(parentWidget);

    try {
        QChartView *chartView = createBMSFChart();
        if (chartView) {
            setupChartLayout(parentWidget, chartView, QString("BMS F 数据图表 (共%1个数据点)").arg(bmsFData.size()));
            qDebug() << "BMS F 图表绘制完成";
            emit chartDrawn();
        } else {
            emit errorOccurred("BMS F 图表创建失败");
        }
    } catch (const std::exception& e) {
        emit errorOccurred(QString("绘制 BMS F 图表时发生异常: %1").arg(e.what()));
    } catch (...) {
        emit errorOccurred("绘制 BMS F 图表时发生未知异常");
    }
}

// 绘制所有图表
void DrawChart::drawAllCharts(QWidget *parentWidget)
{
    qDebug() << "开始绘制所有图表";

    if (sBmsData.isEmpty() && bmsFData.isEmpty()) {
        emit errorOccurred("没有数据可绘制图表");
        return;
    }

    if (!parentWidget) {
        emit errorOccurred("父部件为空，无法绘制图表");
        return;
    }

    // 清除旧图表
    clearCharts(parentWidget);

    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(parentWidget);
    mainLayout->setContentsMargins(2, 2, 2, 2);
    parentWidget->setLayout(mainLayout);

    // 创建分割器
    QSplitter *splitter = new QSplitter(Qt::Vertical, parentWidget);
    mainLayout->addWidget(splitter);

    try {
        // 创建 S_BMS 图表
        if (!sBmsData.isEmpty()) {
            QWidget *sBmsWidget = new QWidget(splitter);
            QVBoxLayout *sBmsLayout = new QVBoxLayout(sBmsWidget);
            sBmsLayout->setContentsMargins(2, 2, 2, 2);

            QGroupBox *sBmsGroupBox = new QGroupBox(QString("S_BMS 数据图表 (共%1个数据点)").arg(sBmsData.size()));
            QVBoxLayout *groupLayout = new QVBoxLayout(sBmsGroupBox);
            groupLayout->setContentsMargins(2, 2, 2, 2);

            QChartView *chartView = createS_BMSChart();
            if (chartView) {
                groupLayout->addWidget(chartView);
            } else {
                qDebug() << "S_BMS 图表创建失败";
            }

            sBmsLayout->addWidget(sBmsGroupBox);
            splitter->addWidget(sBmsWidget);
        }

        // 创建 BMS F 图表
        if (!bmsFData.isEmpty()) {
            QWidget *bmsFWidget = new QWidget(splitter);
            QVBoxLayout *bmsFLayout = new QVBoxLayout(bmsFWidget);
            bmsFLayout->setContentsMargins(2, 2, 2, 2);

            QGroupBox *bmsFGroupBox = new QGroupBox(QString("BMS F 数据图表 (共%1个数据点)").arg(bmsFData.size()));
            QVBoxLayout *groupLayout = new QVBoxLayout(bmsFGroupBox);
            groupLayout->setContentsMargins(2, 2, 2, 2);

            QChartView *chartView = createBMSFChart();
            if (chartView) {
                groupLayout->addWidget(chartView);
            } else {
                qDebug() << "BMS F 图表创建失败";
            }

            bmsFLayout->addWidget(bmsFGroupBox);
            splitter->addWidget(bmsFWidget);
        }

        // 设置分割器比例
        if (splitter->count() > 0) {
            QList<int> sizes;
            for (int i = 0; i < splitter->count(); ++i) {
                sizes << 400;
            }
            splitter->setSizes(sizes);
        }

        qDebug() << "所有图表绘制完成";
        emit chartDrawn();

    } catch (const std::exception& e) {
        emit errorOccurred(QString("绘制图表时发生异常: %1").arg(e.what()));
    } catch (...) {
        emit errorOccurred("绘制图表时发生未知异常");
    }
}

void DrawChart::saveChartsAsImage(QWidget *parent)
{
    if (!parent) {
        emit errorOccurred("父部件为空，无法保存图表");
        return;
    }

    QString filePath = QFileDialog::getSaveFileName(
        parent,
        "保存图表为图片",
        "",
        "PNG图片 (*.png);;JPEG图片 (*.jpg);;所有文件 (*.*)"
        );

    if (filePath.isEmpty()) {
        return;
    }

    // 查找所有图表视图并保存
    QList<QChartView*> chartViews = parent->findChildren<QChartView*>();
    if (chartViews.isEmpty()) {
        emit errorOccurred("没有找到可保存的图表");
        return;
    }

    bool success = false;
    for (int i = 0; i < chartViews.size(); ++i) {
        QChartView *chartView = chartViews[i];
        if (!chartView) continue;

        QPixmap pixmap = chartView->grab();

        QString savePath;
        if (chartViews.size() == 1) {
            savePath = filePath;
        } else {
            // 多个图表时添加序号
            QFileInfo fileInfo(filePath);
            savePath = fileInfo.path() + "/" + fileInfo.baseName() +
                       "_" + QString::number(i + 1) + "." + fileInfo.suffix();
        }

        if (pixmap.save(savePath)) {
            success = true;
            qDebug() << "图表保存成功:" << savePath;
        } else {
            qDebug() << "图表保存失败:" << savePath;
        }
    }

    if (success) {
        emit errorOccurred("图表保存成功");
    } else {
        emit errorOccurred("图表保存失败");
    }
}

void DrawChart::clearCharts(QWidget *parentWidget)
{
    qDebug() << "清除旧图表";

    if (!parentWidget) return;

    QLayout *layout = parentWidget->layout();
    if (layout) {
        QLayoutItem *child;
        while ((child = layout->takeAt(0)) != nullptr) {
            if (child->widget()) {
                child->widget()->deleteLater();
            }
            delete child;
        }
        delete layout;
    }
}

// 优化后的 S_BMS 数据解析函数
void DrawChart::parseS_BMSData(const QString &line)
{
    try {
        // 优化后的正则表达式，专门匹配包含S_BMS的行
        // 格式: 数字 字母 L数字 S_BMS: 数字 数字,数字,数字,数字
        QRegularExpression regex(R"((\d+)\s+([A-Z])\s+(L\d+)\s+S_BMS:\s+(\d+)\s+(\d+),(\d+),(\d+),(\d+))");
        QRegularExpressionMatch match = regex.match(line);

        if (match.hasMatch()) {
            S_BMSData data;
            data.timestamp = match.captured(1).toInt();
            data.type = match.captured(2)[0];
            data.level = match.captured(3);
            data.id = match.captured(4).toInt();

            // 解析四个数值
            data.values.append(match.captured(5).toInt());
            data.values.append(match.captured(6).toInt());
            data.values.append(match.captured(7).toInt());
            data.values.append(match.captured(8).toInt());

            sBmsData.append(data);
            qDebug() << "解析到 S_BMS 数据:" << data.timestamp << data.type << data.level
                     << "ID:" << data.id << "值:" << data.values;
        } else {
            // 如果标准格式匹配失败，尝试更宽松的匹配
            parseS_BMSDataFallback(line);
        }
    } catch (const std::exception& e) {
        qDebug() << "解析 S_BMS 数据时出错:" << e.what() << "行内容:" << line;
    }
}

// 备用的 S_BMS 数据解析函数，使用更宽松的正则表达式
void DrawChart::parseS_BMSDataFallback(const QString &line)
{
    try {
        // 更宽松的正则表达式，匹配包含S_BMS和逗号分隔数字的行
        QRegularExpression regex(R"((\d+)\s+([A-Z])\s+(L\d+)\s+S_BMS:\s+(\d+)\s+([\d,]+))");
        QRegularExpressionMatch match = regex.match(line);

        if (match.hasMatch()) {
            S_BMSData data;
            data.timestamp = match.captured(1).toInt();
            data.type = match.captured(2)[0];
            data.level = match.captured(3);
            data.id = match.captured(4).toInt();

            // 解析逗号分隔的数值
            QString valuesStr = match.captured(5);
            QStringList valueStrs = valuesStr.split(',');
            for (const QString &valueStr : valueStrs) {
                bool ok;
                int value = valueStr.toInt(&ok);
                if (ok) {
                    data.values.append(value);
                }
            }

            if (data.values.size() >= 4) {
                sBmsData.append(data);
                qDebug() << "使用宽松模式解析到 S_BMS 数据:" << data.timestamp << data.type << data.level
                         << "ID:" << data.id << "值:" << data.values;
            }
        }
    } catch (const std::exception& e) {
        qDebug() << "宽松模式解析 S_BMS 数据时出错:" << e.what() << "行内容:" << line;
    }
}

// 优化后的 BMS F 数据解析函数
void DrawChart::parseBMSFData(const QString &line)
{
    try {
        // 优化后的正则表达式，专门匹配BMS F数据
        QRegularExpression regex(R"((\d+)\s+F\s+BMS\s+([\d\s,\-\[\]\|]+))");
        QRegularExpressionMatch match = regex.match(line);

        if (match.hasMatch()) {
            BMSFData data;
            data.timestamp = match.captured(1).toInt();

            // 获取数值部分
            QString valuesStr = match.captured(2);

            // 清理特殊字符并解析数值
            valuesStr = valuesStr.replace('[', ' ').replace(']', ' ')
                            .replace('|', ' ').replace(',', ' ');

            QStringList valueStrs = valuesStr.split(' ', Qt::SkipEmptyParts);
            for (const QString &valueStr : valueStrs) {
                bool ok;
                double value = valueStr.toDouble(&ok);
                if (ok) {
                    data.values.append(value);
                }
            }

            if (!data.values.isEmpty()) {
                bmsFData.append(data);
                qDebug() << "解析到 BMS F 数据:" << data.timestamp << "数值个数:" << data.values.size();
            }
        }
    } catch (const std::exception& e) {
        qDebug() << "解析 BMS F 数据时出错:" << e.what() << "行内容:" << line;
    }
}

// 设置图表布局的辅助函数
void DrawChart::setupChartLayout(QWidget *parentWidget, QChartView *chartView, const QString &title)
{
    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(parentWidget);
    mainLayout->setContentsMargins(2, 2, 2, 2);
    parentWidget->setLayout(mainLayout);

    // 创建分组框
    QGroupBox *groupBox = new QGroupBox(title);
    QVBoxLayout *groupLayout = new QVBoxLayout(groupBox);
    groupLayout->setContentsMargins(2, 2, 2, 2);

    // 添加图表视图
    groupLayout->addWidget(chartView);

    // 添加到主布局
    mainLayout->addWidget(groupBox);
}

QChartView* DrawChart::createS_BMSChart()
{
    if (sBmsData.isEmpty()) {
        qDebug() << "S_BMS 数据为空，无法创建图表";
        return nullptr;
    }

    try {
        QChart *chart = new QChart();
        chart->setTitle("S_BMS 数据趋势");

        // 创建序列
        QLineSeries *series1 = new QLineSeries();
        series1->setName("值1");

        QLineSeries *series2 = new QLineSeries();
        series2->setName("值2");

        QLineSeries *series3 = new QLineSeries();
        series3->setName("值3");

        QLineSeries *series4 = new QLineSeries();
        series4->setName("值4");

        // 添加数据
        for (int i = 0; i < sBmsData.size(); ++i) {
            const S_BMSData &data = sBmsData[i];
            if (data.values.size() >= 4) {
                series1->append(i, data.values[0]);
                series2->append(i, data.values[1]);
                series3->append(i, data.values[2]);
                series4->append(i, data.values[3]);
            }
        }

        // 添加到图表
        chart->addSeries(series1);
        chart->addSeries(series2);
        chart->addSeries(series3);
        chart->addSeries(series4);

        // 创建坐标轴
        QValueAxis *axisX = new QValueAxis();
        axisX->setTitleText("数据点序号");
        axisX->setLabelFormat("%d");
        chart->addAxis(axisX, Qt::AlignBottom);

        QValueAxis *axisY = new QValueAxis();
        axisY->setTitleText("数值");
        axisY->setLabelFormat("%d");
        chart->addAxis(axisY, Qt::AlignLeft);

        // 附加坐标轴
        series1->attachAxis(axisX);
        series1->attachAxis(axisY);
        series2->attachAxis(axisX);
        series2->attachAxis(axisY);
        series3->attachAxis(axisX);
        series3->attachAxis(axisY);
        series4->attachAxis(axisX);
        series4->attachAxis(axisY);

        // 创建图例
        chart->legend()->setVisible(true);
        chart->legend()->setAlignment(Qt::AlignBottom);

        return createChartView(chart);

    } catch (const std::exception& e) {
        qDebug() << "创建 S_BMS 图表时出错:" << e.what();
        return nullptr;
    }
}

QChartView* DrawChart::createBMSFChart()
{
    if (bmsFData.isEmpty()) {
        qDebug() << "BMS F 数据为空，无法创建图表";
        return nullptr;
    }

    try {
        QChart *chart = new QChart();
        chart->setTitle("BMS F 数据趋势");

        // 找出最大列数
        int maxColumns = 0;
        for (const BMSFData &data : bmsFData) {
            maxColumns = qMax(maxColumns, data.values.size());
        }

        // 限制显示的通道数量，避免图表过于拥挤
        int maxDisplayChannels = 8;
        int displayChannels = qMin(maxColumns, maxDisplayChannels);

        // 创建序列
        QVector<QLineSeries*> seriesList;
        for (int i = 0; i < displayChannels; ++i) {
            QLineSeries *series = new QLineSeries();
            series->setName(QString("通道 %1").arg(i + 1));
            seriesList.append(series);
        }

        // 添加数据
        for (int i = 0; i < bmsFData.size(); ++i) {
            const BMSFData &data = bmsFData[i];
            for (int j = 0; j < qMin(data.values.size(), displayChannels); ++j) {
                seriesList[j]->append(i, data.values[j]);
            }
        }

        // 添加到图表
        for (QLineSeries *series : seriesList) {
            chart->addSeries(series);
        }

        // 创建坐标轴
        QValueAxis *axisX = new QValueAxis();
        axisX->setTitleText("数据点序号");
        axisX->setLabelFormat("%d");
        chart->addAxis(axisX, Qt::AlignBottom);

        QValueAxis *axisY = new QValueAxis();
        axisY->setTitleText("数值");
        axisY->setLabelFormat("%.2f");
        chart->addAxis(axisY, Qt::AlignLeft);

        // 附加坐标轴
        for (QLineSeries *series : seriesList) {
            series->attachAxis(axisX);
            series->attachAxis(axisY);
        }

        // 创建图例
        chart->legend()->setVisible(true);
        chart->legend()->setAlignment(Qt::AlignBottom);

        return createChartView(chart);

    } catch (const std::exception& e) {
        qDebug() << "创建 BMS F 图表时出错:" << e.what();
        return nullptr;
    }
}

QChartView* DrawChart::createChartView(QChart *chart)
{
    if (!chart) {
        qDebug() << "图表为空，无法创建图表视图";
        return nullptr;
    }

    try {
        QChartView *chartView = new QChartView(chart);
        chartView->setRenderHint(QPainter::Antialiasing);
        chartView->setRubberBand(QChartView::RectangleRubberBand); // 支持矩形缩放
        chartView->setMinimumSize(400, 300); // 设置最小尺寸
        return chartView;
    } catch (const std::exception& e) {
        qDebug() << "创建图表视图时出错:" << e.what();
        return nullptr;
    }
}
